<script setup>
import { ref, onMounted, watch } from "vue";
import { pageEmpList, addEmp, getEmpById ,updateEmpById,deleteEmpById} from "@/api/emp";
import { ElMessage,ElMessageBox } from 'element-plus'
import { queryAllDepts } from "@/api/dept";
const searchForm = ref({
  name: "",
  gender: "",
  begin: "",
  end: "",
  dateranges: []
});
const genders = ref([
  { "name": "男", "value": 1 },
  { "name": "女", "value": 2 }

]);
const jobs = ref([
  { "name": "班主任", "value": 1 },
  { "name": "讲师", "value": 2 },
  { "name": "学工主管", "value": 3 },
  { "name": "教研主管", "value": 4 },
  { "name": "咨询师", "value": 5 },
]);
const deptList = ref([])
//定义数据
const empForm = ref({
  "image": "",
  "username": "",
  "name": "",
  "gender": "",
  "job": "",
  "entryDate": "",
  "deptId": "",
  "phone": "",
  "salary": "",
  "exprList": []
});
const tableData = ref([])
const dialogFormVisible = ref(false);
const dialogTitle = ref("新增员工");
const  deleteIds =ref([]);
const userToken =ref("");
function showAddWin() {
  //1.dialog内表单数据置为空 todo
  empForm.value = {
    "image": "",
    "username": "",
    "name": "",
    "gender": "",
    "job": "",
    "entryDate": "",
    "deptId": "",
    "phone": "",
    "salary": "",
    "exprList": []
  };
  //2.将dialog的标题设置为“新增员工”
  dialogTitle.value = "新增员工";
  dialogFormVisible.value = true;
}
//侦听searchForm里的daterangers：如果值有变化，就取开始日期赋值给begin,结束日期赋值给end
watch(() => searchForm.value.dateranges, (newValue, oldValue) => {
  //如果改变之后的新增非空，并且数组的长度为2,再执行：
  if (newValue && newValue.length == 2) {
    searchForm.value.begin = newValue[0];
    searchForm.value.end = newValue[1];
  }
});
//每页数量变化时触发
const handleSizeChange = (val) => {
  pageSize.value = val; //将变化后的每页数量 设置给分页条的每页数量数据项
  //将页码重置为1
  page.value = 1;
  //再向后端发请求
  search();
}

//当前页码变化时触发
const handleCurrentChange = (val) => {
  page.value = val; //将变化后的当前页码 设置给分页条的当前页码
  //重新向后端发请求查询员工列表
  search();

}

//当点击"编辑""按钮的处理逻辑
const handleEdit = async (index, row) => {
  //查询回显  
  const result = await getEmpById(row.id);
  if (result.code == 1) {
    //将查询的数据赋值给empForm
    empForm.value = result.data;
    //给exprList中的exprDate赋值
    const  exprList = empForm.value.exprList;
    exprList.forEach( expr=>{
      //这里，直接给expr赋值，会同步赋值给empList中exprList。因为是对象引用，地址会同步修改
       expr.exprDate=[expr.begin,expr.end]
    });

    //修改对话框标题为“修改员工”
    dialogTitle.value = "修改员工";
    //显示dialog窗口
    dialogFormVisible.value = true;
  }


}
//点击批量删除按钮的处理逻辑
const batchDelete = async ()=>{
  ElMessageBox.confirm(
    '你确定要删除该员工吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      //点击确定，则调用deleteEmpById方法进行删除
      const result = await deleteEmpById(deleteIds.value);
      if (result.code == 1) {
        ElMessage.success('删除员工成功');
        search(); //重新搜索员工列表
      } else {
        ElMessage.error('删除员工失败');
      }
    })
  
};

const handleSelectionChange = (val) => {
   //将复选框中，选中的每条行数据的id存储到一个数据项中
  deleteIds.value=val.map(item=>item.id);
  console.log(deleteIds.value);
}

//当点击""删除"按钮的处理逻辑
const handleDelete = (index, row) => {
ElMessageBox.confirm(
    '你确定要删除该员工吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      //点击确定，则调用deleteEmpById方法进行删除
      const result = await deleteEmpById(row.id);
      if (result.code == 1) {
        ElMessage.success('删除员工成功');
        search(); //重新搜索员工列表
      } else {
        ElMessage.error('删除员工失败');
      }
    })

  console.log(index, row)
}

async function search() {
  //todo暂时page=1,pageSize=5 ,等后续添加了分页功能之后，要获取实际的页码和分页数量
  const result = await pageEmpList(searchForm.value, page.value, pageSize.value);
  console.log(result);
  if (result.code == 1) {
    //取分页查询的列表，设置给表格
    tableData.value = result.data.rows;
    //取分页查询结果的总数量
    total.value = result.data.total;
  } else {
    ElMessage.error("查询员工列表失败");
  }

}
function research() {
  //将搜索条件全部置空
  searchForm.value = {
    name: "",
    gender: "",
    begin: "",
    end: "",
    dateranges: []
  };
  //重新向后端发请求
  search();
}
//页面加载完成
onMounted(async () => {
  search();
  //向后端发请求获取所有部门数据，用于部门下拉框作为下拉选项
  const result = await queryAllDepts();
  if (result.code == 1) {
    deptList.value = result.data;

  }

  //页面一加载，就从localStorage中获取token令牌赋值给userToken
  const loginStr = localStorage.getItem("loginInfo");
  if(loginStr){
    const loginInfo = JSON.parse(loginStr);
    userToken.value =loginInfo.token;
  }

})

const page = ref(1)
const pageSize = ref(5)
const total = ref(0);


//上传文件成功之后的处理.response是响应的结果
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  empForm.value.image = response.data;
}

//上传之前的校验逻辑
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/png') {
    ElMessage.error('不支持的图片格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过 2MB!')
    return false
  }
  return true
}

function addExpr() {
  //js里向数组中添加一个元素:push
  empForm.value.exprList.push({ company: "", job: "", begin: "", end: "", exprDate: [] })
}
function deleteExpr(index) {
  //js里从数组中删除元素:splice（索引,删除数量）,从指定索引开始，删除指定数量
  empForm.value.exprList.splice(index, 1)
}
//侦听empForm里的exprList
watch(() => empForm.value.exprList, (newValue, oldValue) => {
  newValue.forEach(expr => {
    const range = expr.exprDate
    if (range && range.length == 2) {
      expr.begin = expr.exprDate[0];
      expr.end = expr.exprDate[1];
    }
  });
}, { deep: true });
// 提交新增员工确认按钮,将数据发送给后端，保存数据到数据库

async function save() {
  let result;
  //判断id是否为空，不为空执行修改， 如果为空的话，是执行新增
  if(empForm.value.id){
      result = await updateEmpById(empForm.value);
  }else{
      result= await addEmp(empForm.value);
  }
  if (result.code == 1) {
    ElMessage.success('保存成功');
    dialogFormVisible.value = false;
    search();
  } else {
    ElMessage.error('保存失败');
  }

}
</script>

<template>
  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchForm.gender" placeholder="请选择" clearable>
        <el-option v-for="(g, index) in genders" :key="index" :label="g.name" :value="g.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职时间">
      <el-date-picker v-model="searchForm.dateranges" type="daterange" range-separator="到" start-placeholder="开始日期"
        end-placeholder="结束日期" value-format="YYYY-MM-DD" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="research">清空</el-button>
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="showAddWin">
    新增员工
  </el-button>
    <el-button type="primary" @click="batchDelete">
    批量删除
  </el-button>
  <!-- 对话框，里面是一个表单 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="850">
    <el-form :model="empForm" label-width="80px">
      <!-- 使用了layout24栏布局    gutter栅栏间隔  span 栅栏占的列数-->
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="用户名">
            <!-- v-model="form.name" -->
            <el-input v-model="empForm.username" placeholder="请输入员工用户名,2-20个字" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名">
            <!-- v-model="form.name" -->
            <el-input v-model="empForm.name" placeholder="请输入员工姓名,2-10个字" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="性别">
            <!-- v-model="" -->
            <el-select placeholder="请选择性别" v-model="empForm.gender">
              <el-option v-for="(g, index) in genders" :key="index" :label="g.name" :value="g.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号">
            <!-- v-model="form.name" -->
            <el-input placeholder="请输入员工手机号" v-model="empForm.phone" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第3行：职位与薪资 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select placeholder="请选择职位" v-model="empForm.job" style="width:100%">
              <el-option v-for="(j, index) in jobs" :label="j.name" :value="j.value" :key="index" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input placeholder="请输入员工薪资" autocomplete="off" v-model="empForm.salary" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第4行：所属部门与入职日期 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select placeholder="请选择部门" v-model="empForm.deptId" style="width:100%">
              <el-option v-for="(d, index) in deptList" :label="d.name" :value="d.id" :key="d.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker type="date" v-model="empForm.entryDate" value-format="YYYY-MM-DD" placeholder="选择入职日期"
              style="width:100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="头像">
            <!-- 文件上传:并不是使用axios上传的，而是使用了普通表单的形式
             action：文件上传的路径，表单数据提交的路径。需要我们自己手动添加/api前缀
             on-success：当文件上传成功之后的处理函数
             before-upload：文件上传之前的校验,通常用于限制上传的文件格式,大小等的-->
            <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
              :headers="{'token':userToken}"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="empForm.image" :src="empForm.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="工作经历">
            <el-button type="success" @click="addExpr">添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-for="(expr, index) in empForm.exprList" :key="index">
        <el-col :span="9">
          <el-form-item label="时间" label-width="70px">
            <el-date-picker v-model="expr.exprDate" value-format="YYYY-MM-DD" type="daterange" range-separator="到"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公司" label-width="50px">
            <el-input v-model="expr.company" placeholder="请输入公司名称" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位" label-width="50px">
            <el-input v-model="expr.job" placeholder="请输入职位" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button type="danger" @click="deleteExpr(index)">删除</el-button>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-table ref="multipleTableRef" :data="tableData" border @selection-change="handleSelectionChange">
    <el-table-column type="selection" prop="id" width="55" />
    <el-table-column prop="name" label="姓名" width="120" align="center" />
    <el-table-column prop="gender" label="性别" width="120" align="center">
      <template #default="scope">
        {{ scope.row.gender == 1 ? "男" : "女" }}
      </template>
    </el-table-column>
    <el-table-column prop="image" label="头像" width="120" align="center">
      <template #default="scope">
        <img :src="scope.row.image" width="50px">
      </template>
    </el-table-column>
    <el-table-column prop="deptName" label="所属部门" align="center" />
    <!--  1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师 -->
    <el-table-column prop="job" label="职位" align="center">
      <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else>咨询师</span>
      </template>
    </el-table-column>
    <el-table-column prop="entryDate" label="入职日期" align="center" />
    <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>

  </el-table>
  <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />
</template>

<style scoped>
.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>